package it.alertManager.horoscope;

import it.alertManager.exceptions.AlertManagerException;
import it.alertManager.util.CommonData;

import java.io.IOException;
import java.io.StringReader;
import java.util.Locale;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.client.ClientProtocolException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.content.res.Resources;
import android.speech.tts.TextToSpeech;
import android.util.Log;


public class HTTPHoroscopeReader {
	
	private static final String anchorHorosEN = "<div class=\"scontent\">";
	private static final String anchorHorosIT = "<div class=\"oroscopo\">";
	private static final String openParHmlTAG = "<p>";
	
	private static final String LOG_CLASS_NAME = HTTPHoroscopeReader.class.getName();
	
	public String getURLOfDailyHoroscope(String zodiacSign, Locale local) throws AlertManagerException
	{
		Log.d(LOG_CLASS_NAME,"Enter getURLOfDailyHoroscope for loc " + local);
		String urlHoroscopeSite = CommonData.EN_HOROSCOPE_URL + zodiacSign.toLowerCase() + ".php";
		
		if (local.equals(Locale.ITALY))
			urlHoroscopeSite = CommonData.IT_HOROSCOPE_ULR + zodiacSign;
		
		Log.d(LOG_CLASS_NAME,"Exit getURLOfDailyHoroscope ");
		return urlHoroscopeSite;
	}
	
	public void readHoroscopeForIT(Resources res, TextToSpeech textToSpeech, String horoscopeURL) throws AlertManagerException
	{
		Log.d(LOG_CLASS_NAME,"Enter readHoroscopeForIT ");

		String responseBody = CommonData.getResponse(horoscopeURL);
		int start = responseBody.indexOf(anchorHorosIT, 0);
		int end = responseBody.indexOf("</div>", start + anchorHorosIT.length());
		String horoscopeBody = responseBody.substring(start, end);
		
		start = horoscopeBody.indexOf(openParHmlTAG, 0);
		end = horoscopeBody.indexOf("</p>", start + openParHmlTAG.length());			
		horoscopeBody = horoscopeBody.substring(start + openParHmlTAG.length(), end);
		Log.d(LOG_CLASS_NAME,"Complete hoscope message= " + horoscopeBody);	
		textToSpeech.setSpeechRate(CommonData.SPEACH_RATE);
		textToSpeech.speak(horoscopeBody, TextToSpeech.QUEUE_ADD, null);

		Log.d(LOG_CLASS_NAME,"Exit readHoroscopeForIT ");		
	}
	
	public void readHoroscopeForEN(Resources res, TextToSpeech textToSpeech, String horoscopeURL) throws AlertManagerException
	{
		Log.d(LOG_CLASS_NAME,"Enter readHoroscopeForEN ");	
		String responseBody;
		try {
			Log.d(LOG_CLASS_NAME,"Connetting to " + horoscopeURL);	
			responseBody = CommonData.getResponse(horoscopeURL);
			int start = responseBody.indexOf(anchorHorosEN, 0);
			int end = responseBody.indexOf(anchorHorosEN, start + anchorHorosEN.length());
			String horoscopeBody = responseBody.substring(start, end);
			
			// Removing unbalanced tag
			horoscopeBody = horoscopeBody.replaceFirst("\\Q<h3>\\E.*\\Q</h3>\\E", "");
			// Removing anchor tag
			horoscopeBody = horoscopeBody.replaceAll("\\Q<a\\E.*\\Q</a>\\E", "");			
			// Removing tag with attributes
			horoscopeBody = horoscopeBody.replaceAll("\\Qclass=\\E[a-zA-Z>]+", ">");
			
			DocumentBuilder builderHoroscopeURL = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			Document doc = builderHoroscopeURL.parse(new InputSource(new StringReader(horoscopeBody)));
			NodeList imgNodeList = doc.getElementsByTagName("p");
			StringBuffer message = new StringBuffer();
			for (int ik=0; ik < imgNodeList.getLength(); ik++)
			{
				NodeList nodeListPar = imgNodeList.item(ik).getChildNodes();
				if (nodeListPar != null && nodeListPar.item(0) != null)
				{	
					message.append(nodeListPar.item(0).getNodeValue() + " ");
					Log.d(LOG_CLASS_NAME, "NODE VALUE = " + nodeListPar.item(0).getNodeValue());
				}
			}
			textToSpeech.setLanguage(Locale.ENGLISH);
			textToSpeech.setSpeechRate(CommonData.SPEACH_RATE);
			Log.d(LOG_CLASS_NAME, "Complete horoscope message= " + message.toString());			
			textToSpeech.speak(message.toString(), TextToSpeech.QUEUE_ADD, null);
		} catch (ClientProtocolException e) {
			Log.e(LOG_CLASS_NAME, "Error in HTTPHoroscopeReader: " + e.getMessage());
			throw new AlertManagerException("Error in HTTPHoroscopeReader: " + e.getMessage(), e);
		} catch (IOException e) {
			Log.e(LOG_CLASS_NAME, "Error in HTTPHoroscopeReader: " + e.getMessage());
			throw new AlertManagerException("Error in HTTPHoroscopeReader: " + e.getMessage(), e);
		} catch (ParserConfigurationException e) {
			Log.e(LOG_CLASS_NAME, "Error in HTTPHoroscopeReader: " + e.getMessage());
			throw new AlertManagerException("Error in HTTPHoroscopeReader: " + e.getMessage(), e);
		} catch (FactoryConfigurationError e) {
			Log.e(LOG_CLASS_NAME, "Error in HTTPHoroscopeReader: " + e.getMessage());
			throw new AlertManagerException("Error in HTTPHoroscopeReader: " + e.getMessage(), e);
		} catch (SAXException e) {
			Log.e(LOG_CLASS_NAME, "Error in HTTPHoroscopeReader: " + e.getMessage());
			throw new AlertManagerException("Error in HTTPHoroscopeReader: " + e.getMessage(), e);
		}
		finally
		{
			Log.d(LOG_CLASS_NAME,"Exit readHoroscopeForEN ");		
		}		
	}

}
